<?php
if (isset($_GET["aj"])) {
    include '../../class/FunctionsClass.php';
} else {
    include '../class/FunctionsClass.php';
    include '../class/MailControllerClass.php';
    include '../class/ThumbToFile.php';
}
mysql_select_db($database_conn, $conn);
$editFormAction="";
$IMAGES = 7;
$AUDIO = 8;
$VIDEO = 9;
$DOC = 10;
$ZIP = 14;
$PLAIN_TEXT = 15;
$EXE = 16;
$OTHERS = 17;
$INCLUDED_PAGE = 21;
$YES_OPTION = "yes";
$NO_OPTION = "no";
$utility = new Utils();
$SITE_ID = 39;
$siteID = $SITE_ID;
$SITE_URL = "";
$ERROR_MESSAGE = "";
$Site_Group = 43;
$rresult = "";$uploadDiv="";
$admin_function = array("Content", "Category", "Resource", "Group", "Setting", "Feedback", "User", "EmailFriend");

$allSetting = getPageSettings($SITE_ID);
$settings = mysql_fetch_assoc($allSetting);
do {
    $$settings["setting_name"] = $settings["setting_value"];
} while ($settings = mysql_fetch_assoc($allSetting));

$SITE_LOGO_URL = $SITE_URL . "resources/" . getImageURL($SITELOGO);

function stripO($str) {
    $str = str_ireplace(" ", "_", $str);
    $str = str_ireplace(".", "_", $str);
    $str = str_ireplace("'", "", $str);
    return $str;
}

if (!function_exists("GetSQLValueString")) {

    function GetSQLValueString($theValue, $theType, $theDefinedValue = "", $theNotDefinedValue = "") {
        if (PHP_VERSION < 6) {
            $theValue = get_magic_quotes_gpc() ? stripslashes($theValue) : $theValue;
        }

        $theValue = function_exists("mysql_real_escape_string") ? mysql_real_escape_string($theValue) : mysql_escape_string($theValue);

        switch ($theType) {
            case "text":
                $theValue = ($theValue != "") ? "'" . $theValue . "'" : "NULL";
                break;
            case "long":
            case "int":
                $theValue = ($theValue != "") ? intval($theValue) : "NULL";
                break;
            case "double":
                $theValue = ($theValue != "") ? doubleval($theValue) : "NULL";
                break;
            case "date":
                $theValue = ($theValue != "") ? "'" . $theValue . "'" : "NULL";
                break;
            case "defined":
                $theValue = ($theValue != "") ? $theDefinedValue : $theNotDefinedValue;
                break;
        }
        return $theValue;
    }

}

function doLogin($username, $password) {
    mysql_select_db($GLOBALS['database_conn'], $GLOBALS['conn']);
    $query_rs_login = sprintf("select * from admin_user
     WHERE username = %s and user_password =%s", GetSQLValueString($username, "text"), GetSQLValueString($password, "text"));
    return processQuery($query_rs_login);
}

if (isset($_POST['loginfrm'])) {
    $us = $_POST['username'];
    $psd = $_POST['password'];
    $rs_user = doLogin($us, md5($psd));
    if (mysql_num_rows($rs_user) > 0) {
        $row_user = mysql_fetch_assoc($rs_user);
        registerSessions($row_user["username"], $row_user["access_level"], $row_user["admin_user_id"]);
    } else {
        $ERROR_MESSAGE = "<div class='errors redtxt'><h2>Error</h2><span class='normal'>Wrong Username and password. Please Check your Caps Lock</span></div>";
    }
}
$NUMTOVIEW = 50;
//Adding a new Category 
if ((isset($_POST["MM_insert"])) && ($_POST["MM_insert"] == "frmcatadd")) {
    $insertSQL = sprintf("INSERT INTO category (category_name, is_published, category_icon,category_description,list_type, allow_comment,parent_id) VALUES (%s, %s, %s,%s, %s,%s,%s)",
                    GetSQLValueString($_POST['categoryname'], "text"),
                    GetSQLValueString($_POST['ispublished'], "text"),
                    GetSQLValueString($_POST['categoryicon'], "int"),
                    GetSQLValueString($_POST['description'], "text"),
                    GetSQLValueString($_POST['listtype'], "int"),
                    GetSQLValueString($_POST['allowcomment'], "text"),
                    GetSQLValueString($_POST['parentid'], "int"));
    $ctype = "cat";
    mysql_select_db($database_conn, $conn);
    $Result1 = mysql_query($insertSQL, $conn) or die("Error : " . $insertSQL);
    $lastInsert = mysql_insert_id($conn);
    echo $_POST['directlink'];
    if (strlen($_POST['directlink']) > 10)
        $dir = $_POST['directlink'];

    $insertSQL = sprintf("INSERT INTO content (page_title, page_content, is_published,category_id, date_created,source,direct_link,category_type) VALUES (%s, %s,%s, %s, now(),%s,%s,%s)",
                    GetSQLValueString($_POST['categoryname'], "text"),
                    GetSQLValueString(stripUslessCharacters($_POST['pcontent']), "text"),
                    GetSQLValueString($_POST['ispublished'], "text"),
                    GetSQLValueString($lastInsert, "int"),
                    GetSQLValueString($_POST['source'], "text"),
                    GetSQLValueString($dir, "text"),
                    GetSQLValueString($ctype, "text")); //redirect("./?page=category&itemid=".$lastInsert);
    mysql_select_db($database_conn, $conn);
    $Result1 = mysql_query($insertSQL, $conn) or die("Error : " . $insertSQL);
}

//Image Precessing
if ((isset($_POST["MM_insert"])) && ($_POST["MM_insert"] == "frmContentAdd")) {
    if ($_POST['listtype'] == 2 || $_POST['listtype'] == 3) {
        $insertSQL = sprintf("INSERT INTO content (tags, page_title, page_content, page_banner, category_id, is_published,last_modified,date_created,category_type,source) VALUES (%s, %s, %s, %s, %s,  %s,%s,%s,'page',%s)",
                        GetSQLValueString($_POST['keywords'], "text"),
                        GetSQLValueString($_POST['ptitle'], "text"),
                        GetSQLValueString(stripUslessCharacters($_POST['pcontent']), "text"),
                        GetSQLValueString($_POST['pbanner'], "int"),
                        GetSQLValueString($_POST['categoryid'], "int"),
                        GetSQLValueString($_POST['ispublished'], "text"),
                        GetSQLValueString($_POST['lastmodified'] . " " . $_POST['tendH'] . ":" . $_POST['tendM'] . ":00", "text"),
                        GetSQLValueString($_POST['datecreated'] . " " . $_POST['tstartH'] . ":" . $_POST['tstartM'] . ":00", "text"),
                        GetSQLValueString($_POST['source'], "text"));
    } else {

        $insertSQL = sprintf("INSERT INTO content (tags, page_title, page_content, page_banner, category_id, is_published,date_created,last_modified,category_type,source) VALUES (%s, %s, %s, %s, %s,  %s,now(),now(),'page',%s)",
                        GetSQLValueString($_POST['keywords'], "text"),
                        GetSQLValueString($_POST['ptitle'], "text"),
                        GetSQLValueString(stripUslessCharacters($_POST['pcontent']), "text"),
                        GetSQLValueString($_POST['pbanner'], "int"),
                        GetSQLValueString($_POST['categoryid'], "int"),
                        GetSQLValueString($_POST['ispublished'], "text"),
                        GetSQLValueString($_POST['source'], "text"));
    }
    mysql_select_db($database_conn, $conn);
    $Result1 = mysql_query($insertSQL, $conn) or die(mysql_error());
    $contentid = mysql_insert_id($conn);
}
if ((isset($_POST["MM_update"])) && ($_POST["MM_update"] == "frmcontentUpdate")) {
    $dir = "";
    if (isset($_POST['isDirect']) && strlen($_POST['directlink']) > 1)
        $dir = $_POST['directlink'];

    if ($_POST["listtype"] == 2 || $_POST["listtype"] == 3 || $_POST["listtype"] == 4) {

        $updateSQL = sprintf("UPDATE content SET tags=%s, page_title=%s, page_content=%s, page_banner=%s, is_published=%s, category_id=%s, direct_link=%s, `last_modified`=%s, date_created=%s , source=%s WHERE content_id=%s",
                        GetSQLValueString($_POST['keywords'], "text"),
                        GetSQLValueString($_POST['ptitle'], "text"),
                        GetSQLValueString(stripUslessCharacters($_POST['pcontent']), "text"),
                        GetSQLValueString($_POST['pbanner'], "int"),
                        GetSQLValueString($_POST['ispublished'], "text"),
                        GetSQLValueString($_POST['categoryid'], "int"),
                        GetSQLValueString($dir, "text"),
                        GetSQLValueString($_POST['lastmodified'] . " " . $_POST['tendH'] . ":" . $_POST['tendM'] . ":00", "text"),
                        GetSQLValueString($_POST['datecreated'] . " " . $_POST['tstartH'] . ":" . $_POST['tstartM'] . ":00", "text"),
                        GetSQLValueString($_POST['source'], "text"),
                        GetSQLValueString($_POST['contentid'], "int"));
    } else {
        $updateSQL = sprintf("UPDATE content SET tags=%s, page_title=%s, page_content=%s, page_banner=%s, is_published=%s, category_id=%s, direct_link=%s, `last_modified`=now() , source=%s WHERE content_id=%s",
                        GetSQLValueString($_POST['keywords'], "text"),
                        GetSQLValueString($_POST['ptitle'], "text"),
                        GetSQLValueString(stripUslessCharacters($_POST['pcontent']), "text"),
                        GetSQLValueString($_POST['pbanner'], "int"),
                        GetSQLValueString($_POST['ispublished'], "text"),
                        GetSQLValueString($_POST['categoryid'], "int"),
                        GetSQLValueString($dir, "text"),
                        GetSQLValueString($_POST['source'], "text"),
                        GetSQLValueString($_POST['contentid'], "int"));
    }


    mysql_select_db($database_conn, $conn);
    $Result1 = mysql_query($updateSQL, $conn) or die(mysql_error());
    $contentid = $_POST['contentid'];
}

    $msg="";
    $filetype="";
/* -- Adding Images */
if (isset($_POST['addimgs'])) {
    $plusloc = "";
    $dirname = $utility->urlFriendly($_POST['dirname']);
    if (strlen($dirname)) {
        if (is_dir("../resources/images/" . $dirname)) {
            $plusloc = $dirname . "/";
        } else {

            mkdir("../resources/images/" . $dirname);
            $plusloc = $dirname . "/";
        }
    }
    $filenames = array("", "images", "audio", "video", "text", "zip", "docs", "forms", "others");
    $arrayResource = array();
    $cnt = 0;
    $imageNum = $_REQUEST['uploadnum'];
    for ($i = 1; $i <= $imageNum; $i++) {
$f="";
//echo "File : ".$i;
        if ((@$_FILES["file$i"]["size"] < 200000000)) {
            //echo "<br />Type : ".$_FILES["file$i"]["type"];
            //echo "<br />Size : ".$_FILES["file$i"]["size"];

            if (( @$_FILES["file$i"]["type"] == "image/gif")
                    || (@$_FILES["file$i"]["type"] == "image/jpeg") || (@$_FILES["file$i"]["type"] == "image/png")
                    || (@$_FILES["file$i"]["type"] == "image/pjpeg")) {
                // echo "Image found";
                $filetype = $IMAGES;
                $f = 1;
            } elseif (@$_FILES["file$i"]["type"] == "application/pdf" || @$_FILES["file$i"]["type"] == "application/msword" || @strripos($_FILES["file$i"]["type"], "application/vnd.openxmlformats-officedocument") > 0) {
                $filetype = $DOC;
                $f = 6;
            } elseif (@$_FILES["file$i"]["type"] == "application/zip") {
                $filetype = $ZIP;
                $f = 5;
            } elseif (@$_FILES["file$i"]["type"] == "application/x-shockwave-flash") {
                $filetype = $VIDEO;
                $f = 3;
            } elseif (@$_FILES["file$i"]["type"] == "audio/mpeg") {
                $filetype = $AUDIO;
                $f = 2;
            } elseif (@$_FILES["file$i"]["type"] == "text/plain") {
                $filetype = $PLAIN_TEXT;
                $f = 6;
            } elseif (@$_FILES["file$i"]["type"] == "text/html" || @$_FILES["file$i"]["type"] == "application/x-php") {
                $filetype = $INCLUDED_PAGE;
                $f = 7;
            }
        } else {
            $filetype = $INCLUDED_PAGE;
            $f = 8;
        }
// echo $filetype." - ||- ";
     //   echo $filenames[$f] . " $f " . $_FILES["file$i"]["type"];
        if ($filetype != NULL && $filetype > 0) {
            // echo "FIle type error";
            if ($_FILES["file$i"]["error"] > 0) {
                $msg = "Return Code:  " . $_FILES["file$i"]["error"] . " File had errors<br />";
            } else {

                $lastResource = getLastResource();
                $lastResource+=1;
                $fileExtensionStarts = strrpos($_FILES["file$i"]["name"], '.');
                $fileNameOnly = $utility->urlFriendly(substr($_FILES["file$i"]["name"], 0, $fileExtensionStarts), "_");
                $fileExtension = substr($_FILES["file$i"]["name"], $fileExtensionStarts);
                $filenm = $fileNameOnly . $fileExtension;

                $destinationOnly = "resources/" . $filenames[$f] . "/" ;

                if ($filenames[$f] == "images") {
                    $destination = $plusloc . "" . $lastResource . "_" . $filenm;
                }
                else
                    $destination =  $lastResource . "_" . $filenm;
                $destination = substr($destination,0, strripos($destination, "."));
                $resize=0;
          if(isset($_POST["resizeChk$i"]))
              $resize=680;

                uploadFile("file$i",$fileType, "../".$destinationOnly,200000000,$destination,false,$resize);
                //move_uploaded_file($_FILES["file$i"]["tmp_name"], "../" . $destination);
                //if($filenames[$f]=="images")
                $img = $filenames[$f] . "/" . $plusloc . $lastResource . "_" . $filenm;
                //  else
                //     $img = $filenames[$f]."/".$lastResource."_".$filenm;

                $insertSQL = sprintf("INSERT INTO resource (category_id,resource_url,resource_description) VALUES (%s, %s, %s)",
                                GetSQLValueString($filetype, "text"),
                                GetSQLValueString($img, "text"),
                                GetSQLValueString(stripUslessCharacters($_POST["pdesc" . $i]), "text"));

                mysql_select_db($database_conn, $conn);
                $Result1 = mysql_query($insertSQL, $conn) or die(mysql_error());
                $arnt = mysql_insert_id($conn);
                if ($_POST['resourceonly'] != "yes" && !isset($_POST['resourceonly'])) {
                    addResources($arnt, $contentid);
                }
                $cnt++;
            }
        } else {

            $msg.="File Not valid";
        }
    }
}
/* --End of adding images */

//echo $msg;
foreach ($_POST as $key => $val) {
    if (substr($key, 0, 10) == "delchk123_") {
        if (!resourceConnectionExist($val, $contentid)) {
            $query = "INSERT INTO  content_resource  (resource_id,content_id) values('$val','$contentid')";
            mysql_select_db($database_conn, $conn);
            $Rrs = mysql_query($query, $conn) or die("Unable " . $query);
        }
    } else if (substr($key, 0, 6) == "rpage_") {
        if ($val != $contentid) {
            if (!relatedPageCheck($val, $contentid)) {
                $query = "INSERT INTO  related_pages  (primary_page,secondary_page) values('$val','$contentid')";
                mysql_select_db($database_conn, $conn);
                $Rrs = mysql_query($query, $conn) or die("Unable " . $query);
            }
        }
    }
}

//Updates Form Actions
if (isset($_POST['frmCont'])) {

    $deltab = $_POST['frmCont'];
    $prefix = $_POST['chkprefix'];
    $action = $_POST['frmaction'];

    // echo $deltab ." prefix ".$prefix." action ".$action;
    if ($deltab == "category") {
        foreach ($_POST as $key => $val) {
            if (substr($key, 0, strlen($prefix)) == $prefix) {
                if ($action == "delete") {
                    $query = "delete FROM  category  WHERE  category_id=" . $val . " or parent_id= " . $val;
                    mysql_select_db($database_conn, $conn);
                    $Rrs = mysql_query($query, $conn) or die("Unable " . $query);

                    $q2 = "delete FROM  content  WHERE  category_id=" . $val;
                    mysql_select_db($database_conn, $conn);
                    $rrs = mysql_query($q2, $conn) or die("Unable " . $query);
                } else if ($action == "approve") {
                    $query = "update   CATEGORY  set is_published='" . $YES_OPTION . "'  where category_id=" . $val . " ";
                    mysql_select_db($database_conn, $conn);
                    $Rrs = mysql_query($query, $conn) or die("Unable " . $query);
                }
            }
        }
    } else if ($deltab == "content") {
        foreach ($_POST as $key => $val) {
            if (substr($key, 0, strlen($prefix)) == $prefix) {

                if ($action == "delete") {
                    $query = "delete FROM  content  WHERE  content_id=" . $val;
                    mysql_select_db($database_conn, $conn);
                    $Rrs = mysql_query($query, $conn) or die("Unable " . $query);

                    $query = "delete FROM  category  WHERE  category_id=" . $val;
                    mysql_select_db($database_conn, $conn);
                    $Rrs = mysql_query($query, $conn) or die("Unable " . $query);

                    $query = "delete FROM  content  WHERE  category_id=" . $val;
                    mysql_select_db($database_conn, $conn);
                    $Rrs = mysql_query($query, $conn) or die("Unable " . $query);

                    $query = "delete FROM  content_resource  WHERE  content_id=" . $val;
                    mysql_select_db($database_conn, $conn);
                    $Rrs = mysql_query($query, $conn) or die("Unable " . $query);
                } else if ($action == "approve") {
                    $query = "update   content  set is_published='" . $YES_OPTION . "'  where content_id=" . $val . " ";
                    mysql_select_db($database_conn, $conn);
                    $Rrs = mysql_query($query, $conn) or die("Unable " . $query);
                }
            }
        }
    } else if ($deltab == "resource") {
        foreach ($_POST as $key => $val) {
            if (substr($key, 0, strlen($prefix)) == $prefix) {
                if ($action == "delete") {

                    $resourceurl = getResourceUrl($val);
                    $query = "delete from resource where resource_id=" . $val;
                    mysql_select_db($database_conn, $conn);
                    $Rrs = mysql_query($query, $conn) or die("Unable " . $query);

                    $query = "delete FROM  content_resource  WHERE  resource_id=" . $val;
                    mysql_select_db($database_conn, $conn);
                    $Rrs = mysql_query($query, $conn) or die("Unable " . $query);
                    @unlink("../resources/" . $resourceurl);
                } else if ($action == "approve") {
                    $query = "update resource  set is_published='" . $YES_OPTION . "'  where resource_id=" . $val . " ";
                    mysql_select_db($database_conn, $conn);
                    $Rrs = mysql_query($query, $conn) or die("Unable " . $query);
                }
            }
        }
    } else if ($deltab == "group_mem") {
        foreach ($_POST as $key => $val) {
            if (substr($key, 0, strlen($prefix)) == $prefix) {
                if ($action == "delete") {
                    groupMemberDelete($val);
                }
            }
        }
    }
}
//Add User
if ((isset($_POST["MM_insert"])) && ($_POST["MM_insert"] == "adminuseraddfrm")) {
    $chk = checkUser($_POST['username']);
    if ($chk == true) {
        $msg = "The Username <strong>" . $_POST['username'] . "</strong> has already been used please try another username";
    } else if (strlen($_POST['username']) < 1) {
        $msg = "Username cannot be null ";
    } else {
        foreach ($_POST as $key => $val) {
            if (substr($key, 0, 4) == "achk") {
                $priveleges.=$val . "#";
            }
        }
        $insertSQL = sprintf("INSERT INTO admin_user (username, user_password, email_address, user_privilege, access_level,login_before,account_date) VALUES (%s, %s, %s,%s, %s, 'no', now())",
                        GetSQLValueString($_POST['username'], "text"),
                        GetSQLValueString(md5($_POST['password']), "text"),
                        GetSQLValueString($_POST['email'], "text"),
                        GetSQLValueString($priveleges, "text"),
                        GetSQLValueString($_POST['accesslevel'], "text"));

        $result = processQuery($insertSQL);
        $msg = "User " . $_POST['username'] . " successfully added";
    }
}

//reply contacts
$frmaction = "";
if ($frmaction == "contactreply") {

    $mailer = new MailController();
    $queryResult = $mailer->sendMail($CONTACT_EMAIL, $_POST["sender_email"], $_POST["topic"], $_POST["sender_comment"]);

    updateContact($_GET["itemid"], $_POST["sender_comment"]);
}
//Component Add
if (($frmaction ) == "componentadd") {
    foreach ($_POST as $key => $val) {
        $$key = $val;
    }
    $component = "component/";
    if ($isadd == "yes" || strlen($cat_name) > 0) {

        $dirname = $utility->urlFriendly($cat_name, "-");
        echo "Yes creating a new dir " . $dirname;
        $utility->dirCreate("../" . $component, $dirname);
        $catId = categoryAdd($cat_name, "", 20);
    } else {
        $dirname = $utility->urlFriendly(getCategoryName($component_cat), "-");
    }
    $componentFolder = $component . $dirname;
    $absoluteComponentFolder = "../" . $componentFolder;

    $contentid = contentAdd($component_name, $component_desc, 5020, "page", $dirname);

    if ($_FILES['component_file']['type'] == "application/zip") {

        $basename = $utility->unzipFile($_FILES['component_file']['tmp_name'], $absoluteComponentFolder . "");
        $resourceUrl = $componentFolder . "/" . $basename;
    } else {
        move_uploaded_file($_FILES['component_file']['tmp_name'], $absoluteComponentFolder . "/" . $_FILES['component_file']['name']);
        $resourceUrl = $componentFolder . "/" . $_FILES['component_file']['name'];
    }
    $errorMsg = "Component Adding Successfully to <strong>$resourceUrl</strong>" .
            $resourceid = resourceCreate($resourceUrl, $component_desc, 20);
    addResources($resourceid, $contentid);
}

if (($frmaction ) == "themeadd") {
    foreach ($_POST as $key => $val) {
        $$key = $val;
    }
    $theme = "theme /";
    $themeFolder = $theme;
    $absolutethemeFolder = "../" . $themeFolder;
    $contentid = contentAdd($theme_name, $theme_desc, 5013, "page", "");

    if ($_FILES['theme_file']['type'] == "application/zip") {
        $basename = $utility->unzipFile($_FILES['theme_file']['tmp_name'], $absolutethemeFolder);
        $resourceUrl = $themeFolder . $basename;
        $resourceid = resourceCreate($resourceUrl, $theme_desc, 13);
        addResources($resourceid, $contentid);
        $errorMsg = "Theme Successfully Added at " . $resourceUrl;
    } else {
        $errorMsg = "Fill not a zip file";
    }
}

function updateContact($contactId, $message) {
    $updateSQL = sprintf("update contact_message set is_respond='yes',
                         response_message=%s , response_date = now() where contact_message_id=%s",
                    GetSQLValueString($message, "text"),
                    GetSQLValueString($contactId, "text"));
    processQuery($updateSQL);
}

function redirect($p) {
    header("location:$p");
}

function getCategoryFindList($offset, $ifAll) {
    $q = "select * from category order by category_id desc ";
    if ($ifAll == "NO")
        $q.=" limit $offset , " . $GLOBALS['NUMTOVIEW'];
    return processQuery($q);
}

function getCategoryName($nm) {
    $q = "select category_name from category where category_id=$nm ";
    $r = processQuery($q);
    if (mysql_num_rows($r) > 0)
        return mysql_result($r, 0, "category_name");
    else
        return "None";
}

function categoryAdd($catname, $cat_desc, $parentid) {
    $q = sprintf("insert into category (category_name,category_description, parent_id) values(%s,%s,%s)", GetSQLValueString($catname, "text"),
                    GetSQLValueString($cat_desc, "text"), GetSQLValueString($parentid, "text"));
    processQuery($q);
    return mysql_insert_id();
}

function contentAdd($page_title, $pagetext, $categoryId, $cattype, $extraCode, $created_by="") {
    if (strlen($page_title) > 0) {
        $q = sprintf("insert into content (page_title,page_content,category_id,category_type,extra_code,created_by) values(%s,%s,%s,%s,%s,%s)",
                        GetSQLValueString($page_title, "text"),
                        GetSQLValueString($pagetext, "text"),
                        GetSQLValueString($categoryId, "text"),
                        GetSQLValueString($cattype, "text"),
                        GetSQLValueString($extraCode, "text"),
                        GetSQLValueString($created_by, "text"));
        processQuery($q);

        return mysql_insert_id();
    }return

    0;
}

function getCategoryByParent($catid, $limit = 0, $isAll="yes") {
    $q = "select * from category where parent_id='" . $catid . "'";
    if ($isAll != "yes") {
        $q.=" limit $limit , 50 ";
    }
    return processQuery($q);
}

function getLinksAdmin($user) {
    mysql_select_db($GLOBALS['database_imaCn'], $GLOBALS['imaCn']);
    $myQuery = "select * from admin_user where admin_user_id='$user' ";
    $rs = mysql_query($myQuery, $GLOBALS['imaCn']) or die(mysql_error() . " Error - $linkType " . $myQuery);
    return $rs;
}

function getCategoryDetails($catid) {
    $q = "select * from category where category_id= $catid";

    return processQuery($q);
}

function searchCategory($ps) {
    $q = "select * from category where category_name like '%$ps%'";
    return processQuery($q);
}

function resourceConnectionExist($resourceid, $contentid) {
    $q = "select * from content_resource where content_id=$contentid and resource_id=$resourceid";
    if (mysql_num_rows(processQuery($q)) > 0)
        return true;
    else
        return false;
}

function relatedPageCheck($pg1, $pg2) {
    $q = "select * from related_pages where (primary_page=$pg1 and secondary_page=$pg2) or (primary_page=$pg2 and secondary_page=$pg1) ";
    if (mysql_num_rows(processQuery($q)) > 0)
        return true;
    else
        return false;
}

function getResourceUrl($resourceid) {
    $q = "select * from resource where resource_id=$resourceid";
    $r = processQuery($q);
    return mysql_result($r, 0, "resource_url");
}

function getContentList($offset, $ifAll) {

    $q = "select * from content order by content_id   desc ";
    if ($ifAll == "NO")
        $q.=" limit $offset , " . $GLOBALS['NUMTOVIEW'];
    return processQuery($q);
}

function getCatContentList($catId, $offset, $ifAll) {
    $q = "select * from content where order by content_id desc ";
    if ($ifAll == "NO")
        $q.=" limit $offset , " . $GLOBALS['NUMTOVIEW'];
    return processQuery($q);
}

function getComponentTheme($catid, $resourceCat, $limit, $isAll) {
    $q = "select  content.content_id, page_title, extra_code,content.category_id, resource_url
        from  content inner join content_resource inner join resource
        on content.content_id = content_resource.content_id
        and resource.resource_id =content_resource.resource_id
        where resource.category_id =$resourceCat and content.category_id =$catid
        limit $limit , " . $GLOBALS['NUMTOVIEW'];

    if (strtolower($isAll) == "yes")
        $q = "select count(content.content_id) as counter  from  content inner join content_resource inner join resource
        on content.content_id = content_resource.content_id
        and resource.resource_id =content_resource.resource_id
        where resource.category_id =$resourceCat and content.category_id =$catid";
    return processQuery($q);
}

function searchComponentTheme($searchParam, $catid, $resourceCat) {
    $q = "select  content.content_id, page_title, extra_code,content.category_id, resource_url
        from  content inner join content_resource inner join resource
        on content.content_id = content_resource.content_id
        and resource.resource_id =content_resource.resource_id
        where resource.category_id =$resourceCat and content.category_id =$catid
        and(page_title like '%$searchParam%' or extra_code like '%$searchParam%' or resource_url like '%$searchParam%' or page_content like '%$searchParam%')
            ";
    return processQuery($q);
}

function getContentCatList($itemid, $offset, $ifAll) {
    $q = "select * from content where categoryid=$itemid ";
    if ($ifAll == "NO")
        $q.=" limit $offset , " . $GLOBALS['NUMTOVIEW'];
    return processQuery($q);
}

function getResourceList($offset, $ifAll, $site_id='common') {
    $q = "select * from resource  where resource.site_id='$site_id' or resource.site_id='common' ";
    if ($ifAll == "NO")
        $q.=" limit $offset , " . $GLOBALS['NUMTOVIEW'];
    return processQuery($q);
}

function getResourceListDesc($offset, $ifAll, $site_id='common') {
    $q = "select * from resource   inner join category on resource.category_id = category.category_id  where resource.site_id='$site_id' or resource.site_id='common' ";
    if ($ifAll == "NO")
        $q.=" order by resource_id desc limit $offset , " . $GLOBALS['NUMTOVIEW'];
    return processQuery($q);
}

function getContentByCat($catid, $offset, $ifAll) {
    $q = "select * from content where category_id =$catid ";
    if ($ifAll == "NO") {
        $q.=" limit $offset , " . $GLOBALS['NUMTOVIEW'];
    } else {
        $q = "select count(content_id) as pg from content where category_id=$catid";

        $result = processQuery($q);
        $as = mysql_fetch_assoc($result);
        return $as["pg"];
    }
    return processQuery($q);
}

function searchContent($ps) {
    $q = "select * from content where page_title like '%$ps%' or content_id='$ps'";

    return processQuery($q);
}

function searchResources($ps) {
    $q = "select * from resource inner join category
	on resource.category_id =category.category_id where resource_url  like '%$ps%' or resource_description  like '%$ps%' or resource_id  like '%$ps%'  limit 0,20";
    return processQuery($q);
}

function getLastResource() {
    $q = "select resource_id from resource order by resource_id desc limit 0,1";
    $id = mysql_result(processQuery($q), 0, "resource_id");
    //echo $id."Last Id ";
    return mysql_result(processQuery($q), 0, "resource_id");
}

function getContentDetails($colname_rs_up) {
    $q = sprintf("SELECT * FROM content WHERE content_id = %s", GetSQLValueString($colname_rs_up, "int"));
    return processQuery($q);
}

function getContentPageTitle($colname_rs_up) {
    $q = sprintf("SELECT page_title FROM content WHERE content_id = %s", GetSQLValueString($colname_rs_up, "int"));
    $rs = processQuery($q);
    return mysql_result($rs, 0, "page_title");
}

function getContentResource($contentid) {
    $q = "select resource.resource_id,content_resource.content_id,category_name,resource_url,resource_description from
		content_resource inner join resource inner join category on
		content_resource.resource_id = resource.resource_id  and resource.category_id = category.category_id
		where content_resource.content_id=$contentid";

    return processQuery($q);
}

function getContentResourceByCategory($contentid, $cat) {
    $q = "select resource.resource_id,content_resource.content_id,category_name,resource_url,resource_description from
		content_resource inner join resource inner join category on
		content_resource.resource_id = resource.resource_id  and resource.category_id = category.category_id
		where content_resource.content_id=$contentid and resource.category_id=$cat";
    return processQuery($q);
}

if ((isset($_POST["MM_update"])) && ($_POST["MM_update"] == "frmcatupdate")) {
    $updateSQL = sprintf("UPDATE category SET category_name=%s, is_published=%s, category_icon=%s,category_description=%s, list_type=%s, parent_id=%s , allow_comment =%s ,is_rss=%s  WHERE category_id=%s",
                    GetSQLValueString($_POST['categoryname'], "text"),
                    GetSQLValueString($_POST['ispublished'], "text"),
                    GetSQLValueString($_POST['categoryicon'], "int"),
                    GetSQLValueString($_POST['description'], "text"),
                    GetSQLValueString($_POST['listtype'], "int"),
                    GetSQLValueString($_POST['parentid'], "int"),
                    GetSQLValueString($_POST['allowcomment'], "text"),
                    GetSQLValueString($_POST['rss'], "text"),
                    GetSQLValueString($_POST['categoryid'], "int"));

    mysql_select_db($database_conn, $conn);
    $Result1 = mysql_query($updateSQL, $conn) or die(mysql_error());
}

//Add Comment
if ((isset($_POST["MM_insert"])) && ($_POST["MM_insert"] == "frmcommentAdd")) {
    $insertSQL = sprintf("INSERT INTO user_comment (user_id, comment_title, user_comment_message, content_id, is_publish, site_id,user_comment_response) VALUES (%s, %s, %s, %s, %s, %s, %s)",
                    GetSQLValueString($_POST['user_id'], "text"),
                    GetSQLValueString($_POST['comment_title'], "text"),
                    GetSQLValueString($_POST['user_comment_message'], "text"),
                    GetSQLValueString($_POST['content_id'], "int"),
                    GetSQLValueString($_POST['is_publish'], "text"),
                    GetSQLValueString($_POST['site_id'], "text"),
                    GetSQLValueString($_POST['user_comment_response'], "text"));

    processQuery($insertSQL);
}
//update Comment
if ((isset($_POST["MM_update"])) && ($_POST["MM_update"] == "frmCommentUpdate")) {
    $updateSQL = sprintf("UPDATE user_comment SET user_id=%s, comment_title=%s, user_comment_message=%s, comment_date=%s, content_id=%s, is_publish=%s, site_id=%s WHERE user_comment_id=%s",
                    GetSQLValueString($_POST['user_id'], "text"),
                    GetSQLValueString($_POST['comment_title'], "text"),
                    GetSQLValueString($_POST['user_comment_message'], "text"),
                    GetSQLValueString($_POST['comment_date'], "date"),
                    GetSQLValueString($_POST['content_id'], "int"),
                    GetSQLValueString($_POST['is_publish'], "text"),
                    GetSQLValueString($_POST['site_id'], "text"),
                    GetSQLValueString($_POST['user_comment_id'], "int"));

    processQuery($updateSQL);
}

function getSiteBanners() {
    global $SITE_ID;
    $query = "select resource_url,resource.resource_id from category inner join content inner join content_resource inner join resource
	on  category.category_id = content.category_id
	and content.content_id = content_resource.content_id
        and resource.resource_id = content_resource.resource_id
where parent_id=$SITE_ID  and category_name like '%banner%'
            ";
    return processQuery($query);
}

function getSubCategoryFind($parentid, $offset, $ifAll) {
    $q = "select * from category inner join content on category.category_id=content.category_id where parent_id = $parentid";

    if ($ifAll == "NO")
        $q.=" limit $offset , " . $GLOBALS['NUMTOVIEW'];
    return processQuery($q);
}

//Setting Functions
function getPageSettings($site) {
    $q = "select * from setting where site_id='common' or site_id='$site'";

    return processQuery($q);
}

function getPageSettingsDetails($settingname) {
    $q = "select * from setting where setting_name = '" . $settingname . "'";
    return processQuery($q);
}

function getContactList($startRow_rs_service, $maxRows_rs_service, $all) {
    //  ,sender_telephone,topic,sender_comment,date_posted,is_respond,site_id
    $query_rs_service = "SELECT contact_message_id,sender_name,sender_email,topic,date_posted from contact_message order by date_posted desc ";
    if (strtoupper($all) == "YES") {
        $query_limit_rs_service = "select count(contact_message_id) as count from contact_message ";
        $rs_service = processQuery($query_limit_rs_service);
        return mysql_result($rs_service, 0, "count");
    } else {

        $query_limit_rs_service = sprintf("%s LIMIT %d, %d", $query_rs_service, $startRow_rs_service, $maxRows_rs_service);
    }
    $rs_service = processQuery($query_limit_rs_service);

    return $rs_service;
}

function getContactDetails($contactid) {
    $query_rs_service = "SELECT * from contact_message  where contact_message_id=$contactid";
    $query_limit_rs_service = sprintf("%s ", $query_rs_service);
    $rs_service = processQuery($query_limit_rs_service);
    return $rs_service;
}

//------------------------------------------------
function getUserList() {
    $query_rs_service = "select * from admin_user ";
    $query_limit_rs_service = sprintf("%s ", $query_rs_service);
    $rs_service = processQuery($query_limit_rs_service);
    return $rs_service;
}

function checkUser($username) {
    $username = GetSQLValueString($username, "text");
    $query_rs_service = "select admin_user_id from  admin_user where username=$username";

    $query_limit_rs_service = sprintf("%s ", $query_rs_service);
    $rs_service = processQuery($query_limit_rs_service);

    if (mysql_num_rows($rs_service) > 0)
        return true;
    else
        return false;
}

function getUserCommentList($contentId, $offset, $isAll) {

    if (strtolower($isAll) == "no") {
        $query = "select * from user_comment where content_id = $contentId limit $offset, 50 ";
        return processQuery($query);
    } else {
        $query = "select count(user_comment_id) as cnt from user_comment where content_id =$contentId";
        $res = processQuery($query);
        return mysql_result($res, 0, "cnt");
    }
}

function deleteUserComment($commentId) {
    $query = "delete from user_comment where user_comment_id = $commentId";
    processQuery($query);
    echo "Comment Deleted Successfully";
}

function approveComment($commentId) {

}

function getUserComment($offset, $all, $functionid, $itemid) {
    $query_rs_service = "SELECT commentid,usercomment.userid,usercomment,commentdate,ispublish,username FROM
                         usercomment inner join userregistration
on usercomment.userid = userregistration.userid
where functionid='$functionid' and itemid='$itemid'
            ";
    if ($all == "NO")
        $query_rs_service.=" limit $offset, 50";

    $query_limit_rs_service = sprintf("%s ", $query_rs_service);
    $rs_service = processQuery($query_limit_rs_service);
    return $rs_service;
}

function getUserCommentDetails($commentid) {
    $query_rs_service = "SELECT * FROM user_comment where user_comment_id=$commentid ";
    echo $query_rs_service;
    $query_limit_rs_service = sprintf("%s ", $query_rs_service);
    $rs_service = processQuery($query_limit_rs_service);
    return $rs_service;
}

function getUserDetails($commentid) {
    $query_rs_service = "SELECT * from userregistration where userid=$commentid";

    $query_limit_rs_service = sprintf("%s ", $query_rs_service);
    $rs_service = processQuery($query_limit_rs_service);
    return $rs_service;
}

if ((isset($_POST["MM_update"])) && ($_POST["MM_update"] == "frmeditsetting")) {
    $updateSQL = sprintf("UPDATE setting SET setting_value=%s WHERE setting_name=%s",
                    GetSQLValueString($_POST['settingvalue'], "text"),
                    GetSQLValueString($_POST['settingname'], "text"));
    mysql_select_db($database_conn, $conn);
    $Result1 = mysql_query($updateSQL, $conn) or die(mysql_error());
}
if ((isset($_POST["MM_insert"])) && ($_POST["MM_insert"] == "frmaddSetting")) {
    $insertSQL = sprintf("INSERT INTO setting (setting_name, setting_value,site_id) VALUES (%s, %s,%s)",
                    GetSQLValueString($_POST['settingname'], "text"),
                    GetSQLValueString($_POST['settingvalue'], "text"),
                    GetSQLValueString($_POST['site'], "text"));

    mysql_select_db($database_conn, $conn);
    $Result1 = mysql_query($insertSQL, $conn) or die(mysql_error());
}

//End of Setting

function addResources($resourceid, $contentid) {

    $q = sprintf("insert into content_resource (content_id,resource_id) values (%s ,%s) ", $contentid, $resourceid);
    processQuery($q);
}

function resourceCreate($resource_url, $resource_desc, $category) {
    $insertSQL = sprintf("INSERT INTO resource (category_id,resource_url,resource_description) VALUES (%s, %s, %s)",
                    GetSQLValueString($category, "text"),
                    GetSQLValueString($resource_url, "text"),
                    GetSQLValueString(stripUslessCharacters($resource_desc), "text"));
    processQuery($insertSQL);
    return mysql_insert_id();
}

function deleteContentResource($val, $content) {
    $query = "delete FROM  content_resource  WHERE  resource_id=" . $val . " and content_id = " . $content;

    $Rrs = processQuery($query);
    echo "Deleted  Resource " . $val;
}

function deleteRelatePages($val, $content) {
    $query = "delete FROM  related_pages  WHERE  (primary_page=" . $val . " and secondary_page = " . $content . ") or (primary_page=" . $content . " and secondary_page =" . $val . ")";

    $Rrs = processQuery($query);
    echo "Deleted  Resource " . $val;
}

function deleteRelatedPage($val, $content) {
    $query = "delete FROM  related_pages  WHERE (primary_page=" . $val . " and secondary_page = " . $content . ") or (primary_page=" . $content . " and secondary_page =" . $val . ")";
    $rrs = processQuery($query);
    echo "Deleted  Related Page " . $val;
}

if ((isset($_POST["MM_update"])) && ($_POST["MM_update"] == "updateResourceFrm")) {
    $updateSQL = sprintf("UPDATE resource SET  resource_description=%s, is_published=%s, source=%s WHERE resource_id=%s",
                    GetSQLValueString($_POST['resourcedesc'], "text"),
                    GetSQLValueString($_POST['ispublished'], "int"),
                    GetSQLValueString($_POST['source'], "text"),
                    GetSQLValueString($_POST['resourceid'], "int"));

    mysql_select_db($database_conn, $conn);
    $Result1 = mysql_query($updateSQL, $conn) or die(mysql_error());
}

function getResourceDetails($resourceid) {
    $q = "select * from resource inner join category on resource.category_id = category.category_id where resource_id=" . $resourceid;
    $rs = processQuery($q);
    return $rs;
}

function getImageURL($resourceid) {
    $result = processQuery("select resource_url from resource where resource_id=$resourceid");
    return @mysql_result($result, 0, "resource_url");
}

function getRelatedPages($contentid) {
    $q = "select * from related_pages where primary_page=" . $contentid . " or secondary_page= " . $contentid;
    $rs = processQuery($q);
    return $rs;
}

function loadRelatedParent($catid) {
    $q = "select parent_id from category where category_id=$catid";
    $r = @mysql_result(processQuery($q), 0, "parent_id");
    if ($r < 1)
        $r = 0;
    $rq = "SELECT * FROM category where parent_id = " . $r;

    $rs = @processQuery($rq);


    return $rs;
}

function loadRelatedContentParent($catid=0, $cattype="") {

    if ($cattype == "page")
        $q = "select content_id as id , page_title as title from content where content_id=$catid";
    else
        $q="select category_id as id , category_name as title from category where category_id=$catid";


    $r = processQuery($q);

    return $r;
}

function published($i) {
    if ($i == 1)
        echo "YES";
    else
        echo "NO";
}

function shortenContent($content, $max) {
    if (strlen($content) <= $max) {
        return $content;
    }else
        return substr($content, 0, $max) . "...";
}

function processQuery($query) {
    mysql_select_db($GLOBALS['database_conn'], $GLOBALS['conn']);
    $rs = mysql_query($query, $GLOBALS['conn']) or die("Error : " . $query . mysql_error());
    return $rs;
}

function getSiteLinks($siteId) {

    $q = "select * from category where category_name='Links' and site_id='" . $siteId . "' and parent_id=$siteId  limit 0,1";

    $result = processQuery($q);
    $linkId = mysql_result($result, 0, "category_id");
    $whereBuilder = "where parent_id = $linkId ";
    $query = "select category_id from category where parent_id = $linkId";
    $qResult = processQuery($query);
    $rowResult = mysql_fetch_assoc($qResult);
    do {
        $whereBuilder.=" or parent_id = " . $rowResult["category_id"];
    } while ($rowResult = mysql_fetch_assoc($qResult));
    $linksQuery = "select category.category_id,category_name,content_id, page_title from category inner join content
                    on category.category_id = content.category_id $whereBuilder";
    $linkResult = processQuery($linksQuery);

    return $linkResult;
}

function getUserTask() {
    $username = GetSQLValueString($_SESSION['maUserAdmin'], "text");
    $whereBuilder = "";
    $query = "select user_privilege from admin_user where username = $username";
    $result = processQuery($query);
    $privileges = mysql_result($result, 0, "user_privilege");

    $privilegeList = explode("#", $privileges);
    $userTask = array();
    $numericCounter = 0;
    $nan = 0;
    for ($i = 0; $i < count($privilegeList); $i++) {
        if (is_numeric($privilegeList[$i])) {
            $numericCounter++;
            if ($numericCounter == 1)
                $whereBuilder.=" where ";
            else
                $whereBuilder.=" or ";
            $whereBuilder.= " content_id = " . $privilegeList[$i];
        }else {
            $nan++;
            $userTask[$nan] = array(
                "page" => strtolower($privilegeList[$i]),
                "title" => $privilegeList[$i],
                "index" => "");
        }
    }
    $taskQuery = "select content_id,page_title from content $whereBuilder ";

    $taskResult = processQuery($taskQuery);
    $taskItems = mysql_fetch_assoc($taskResult);
    do {

        $userTask[$nan] = array(
            "page" => strtolower("page_cat"),
            "title" => $taskItems["page_title"],
            "index" => $taskItems["content_id"]);
        $nan++;
    } while ($taskItems = mysql_fetch_assoc($taskResult));

    return $userTask;
}

function stripUslessCharacters($inputTxt) {
    //  $newscontent = htmlentities($inputTxt);
    $newscontent = str_replace("�", "\"", $inputTxt);
    $newscontent = str_replace("�", "'", $newscontent);
    $newscontent = str_replace("�", "-", $newscontent);
    $newscontent = str_replace("�", "'", $newscontent);
    $newscontent = str_replace("�", "'", $newscontent);
    $newscontent = str_replace("  ", " ", $newscontent);
    $newscontent = str_replace("�", "&cent;", $newscontent);
    $newscontent = str_replace("�", "&pound;", $newscontent);

    $newscontent = str_replace("�", "&agrave;", $newscontent);
    $newscontent = str_replace("�", "&Agrave;", $newscontent);
    $newscontent = str_replace("�", "&Aacute;;", $newscontent);
    $newscontent = str_replace("�", "&aacute;", $newscontent);

    $newscontent = str_replace("�", "&Acirc;", $newscontent);
    $newscontent = str_replace("�", "&acirc;", $newscontent);

    $newscontent = str_replace("�", "&AElig;", $newscontent);
    $newscontent = str_replace("�", "&aelig;", $newscontent);
    $newscontent = str_replace("�", "&Ccedil;", $newscontent);
    $newscontent = str_replace("�", "&ccedil;", $newscontent);

    $newscontent = str_replace("�", "&atilde;", $newscontent);
    $newscontent = str_replace("�", "&Atilde;", $newscontent);
    $newscontent = str_replace("�", "&ecirc;", $newscontent);
    $newscontent = str_replace("�", "&Ecirc;;", $newscontent);

    $newscontent = str_replace("�", "&Eacute;", $newscontent);
    $newscontent = str_replace("�", "&eacute;", $newscontent);
    $newscontent = str_replace("�", "&Egrave;", $newscontent);
    $newscontent = str_replace("�", "&egrave;", $newscontent);

    return $newscontent;
}

function loadRelatedPages($contentid) {
    $rs = getRelatedPages($contentid);
    $r = mysql_fetch_assoc($rs);
    if (mysql_num_rows($rs) > 0) {

        $t = "<div class='dtitle'>Related Pages</div><ul>";
        do {
            $f = $r["page1"];
            if ($f == $contentid)
                $f = $r["page1"];
            $tr = getContentPageTitle($f); /*
              $t.="<li><a href='?".$tr."&page=".$f."'>".$tr."</li>"; */
        }while ($r = mysql_fetch_assoc($rs));
        $t.="</ul>";
    }
}

function getPageResourceList($contentid) {
    $rs = getContentResource($contentid);
    $rr = mysql_fetch_assoc($rs);

    $t = "<ul>";

    do {
        $mainImage = @imagecreatefromjpeg("resources/" . $rr['resource_url']);
        $mainWidth = imagesx($mainImage);
        $mainHeight = imagesy($mainImage);

        $t.="<li><img src='resources/" . $rr['resource_url'] . "'  width='" . $mainWidth . "' height='" . $mainHeight . "'/><div class='imgdesc'>" . $rr['resource_description'] . "</div></li>";
    } while ($rr = mysql_fetch_assoc($rs));
    $t.="</ul>";

    echo $t;
}

function getListType($categoryid) {

    $categoryid = $categoryid;
    if ($categoryid > 4999) {
        $q = "select category_id from content where content_id=$categoryid ";

        $rs = processQuery($q);
        $rr = mysql_fetch_assoc($rs);

        if (mysql_num_rows($rs) > 0) {
            $categoryid = $rr["category_id"];

            while ($categoryid > 4999) {
                $q = "select category_id  from content where content_id=$categoryid";
                //echo $q;
                $rs = processQuery($q);
                $rr = mysql_fetch_assoc($rs);
                $categoryid = $rr["category_id"];
            }
        }
    }
    //echo $categoryid."- Category ";
    $q2 = "select list_type,allow_comment from category where category_id=$categoryid";
    //echo $q2;
    $rs2 = processQuery($q2);


    return $rs2;
}

function getSiteList() {
    global $ADV_SITE;
    $query = "select * from category where parent_id = $ADV_SITE ";
    $result = processQuery($query);
    return $result;
}

function updateSite() {
    updateCategory($_POST['site_id'], $_POST['site_initial'], $_POST['site_name']);
}

function updateSetting($settingName, $settingValue) {
    $query = "update setting set setting_value=" . GetSQLValueString($settingValue, "text");
    processQuery($query);
}

function updateCategory($categoryId, $categoryName, $categoryDesc) {
    $query = "update category set category_name=" . GetSQLValueString($categoryName, "text") . " category_description= " . GetSQLValueString($categoryDesc, "text") . " where category_id = " . $categoryId;
    processQuery($query);
}

function updateContent($contentId, $pageTitle, $pageContent) {
    $query = "update category set page_=" . GetSQLValueString($pageTitle, "text") . " page_content= " . GetSQLValueString($pageContent, "text") . " where category_id = " . $contentId;
    processQuery($query);
}

function createComboList($num, $selected) {
    $d = "";
    for ($i = 0; $i < $num; $i++) {
        $ot = $i;
        if ($i < 10) {
            $ot = "0$i";
        }
        $d.="<option value='$ot' ";
        if ($i == $selected)
            $d.="selected='selected'";
        $d.=">" . $ot . "</option>";
    }
    return $d;
}

function createYesNoCombo($selected) {
    if (ucwords($selected) == "YES")
        $yesSelected = "selected='selected'";
    else if (ucwords($selected) == "NO")
        $noSelected = "selected='selected'";
    return "<option value='yes' $yesSelected>YES</option><option value='no' $noSelected>NO</option>";
}

function checkResourceExist($fileType, $folder, $resourceUrl) {
    $q = "select resource_id from resource where resource_url like '$folder%$resourceUrl'";

    $r = processQuery($q);

    if (mysql_num_rows($r) > 0) {
        return true;
    }else
        return false;
}

function getFileTypes() {
    $q = "select * from category where parent_id=5";
    return processQuery($q);
}

function addResource($fileType, $url) {
    $insertSQL = sprintf("INSERT INTO resource (category_id,resource_url) VALUES (%s, %s)",
                    GetSQLValueString($fileType, "text"),
                    GetSQLValueString($url, "text"));
    processQuery($insertSQL);
}

if (isset($_POST['check_uploads'])) {
    $rresult = checkUploadedFiles($_POST['file_type'], $_POST['folder']);
}

function siteCategoriesByItem($item, $site) {
    $q = "select * from category where parent_id = $site and category_name like '%$item%' order by category_id limit 0,1";
    $rs = processQuery($q);
    $itemId = mysql_result($rs, 0, "category_id");

    $query = "select category_id,category_name from category  where parent_id= $itemId order by category_id ";
    $result = processQuery($query);

    return $result;
}

function checkUploadedFiles($fileType, $folder) {
    // Define the full path to your folder from root
    $fileResults = "";
    $path = "../resources/" . $folder . "/";
    // Open the folder

    $dir_handle = @opendir($path) or die("Unable to open $path");

    // Loop through the files
    while ($file = readdir($dir_handle)) {
        if ($file == "." || $file == ".." || $file == "index.php" || is_dir($path . $file))
            continue;
        $resourceUrl = $file;
        $fCount = 0;
        if (!checkResourceExist($fileType, $folder, $resourceUrl)) {
            addResource($fileType, $folder . "/" . $resourceUrl);
            $fileResults.="File added successfully : " . $resourceUrl . "<br />";
            $fCount = $fCount + 1;
        } else {

        }
    }

    if ($fCount == 0

        )$fileResults = " <span class='redtxt'>No New File Found </span>";
    // Close
    closedir($dir_handle);
    return "No of Files : " . $fCount . "<br />Folder : $folder<br />" . $fileResults;
}

function getFieldFromDatabase($tableName, $field, $search_by, $tableId) {
    $q = " select $field from $tableName where $search_by = $tableId";
    $results = processQuery($q);
    return @mysql_result($results, 0, "$field");
}

//<editor-fold desc="group functions">
function groupAdd() {

}

function groupEdit() {

}

function groupDelete($groupID) {
    $q = "delete from category where category_id=\"$groupID\"";
    $result = processQuery($q);
    $q = "delete from group_member where group_id=\"$groupID\"";
    $result = processQuery($q);
}

function groupMemberEdit() {
    $insertSQL = sprintf("UPDATE group_member SET group_id= %s, content_id=%s, group_member_title=%s, group_order=%s, `description`=%s, group_direct_link=%s, group_member_resource=%s where group_member_id=%s",
                    GetSQLValueString($_POST['group_id'], "int"),
                    GetSQLValueString($_POST['content_id'], "int"),
                    GetSQLValueString($_POST['group_member_title'], "text"),
                    GetSQLValueString($_POST['group_order'], "int"),
                    GetSQLValueString($_POST['description'], "text"),
                    GetSQLValueString($_POST['group_direct_link'], "text"),
                    GetSQLValueString($_POST['group_member_resource'], "int"),
                    GetSQLValueString($_POST['group_member_id'], "int"));
    $result = processQuery($insertSQL);
}

function groupMemberDelete($groupID) {
    $q = "delete from group_member where group_member_id=\"$groupID\"";
    $result = processQuery($q);
}

$MM_insert = "";
$query_result = "";
if (isset($_POST["MM_insert"]))
    $MM_insert = $_POST["MM_insert"];
if ($MM_insert == "groupAddFrm") {
    groupMemberAdd();
} else if ($MM_insert == "groupEditFrm") {
    groupMemberEdit();
} else if ($MM_insert == "query") {
    $qs = queryProcess($_POST["query"]);
    $query_result = mysql_affected_rows() . " Rows Affected ";
    $table = "<table class='datatable' width='100%'>";
    $row = mysql_fetch_array($qs);
    do {
        $cnt = count($row) / 2;
        $table.= "<tr class='" . "" . "'>";
        for ($i = 0; $i < $cnt; $i++) {
            $table.="<td>" . $row[$i] . "</td>";
        }
        $table.= "</tr>";
    } while ($row = mysql_fetch_array($qs));
    $table.="</table>";
} else if ($MM_insert == "uploads") {
   $uploadDiv =  uploadFiles();
}

function queryProcess($query) {
    $rs = processQuery($query);
    return $rs;
}

function groupMemberAdd() {
    $insertSQL = sprintf("INSERT INTO group_member (group_id, content_id, group_member_title, group_order, `description`, group_direct_link, group_member_resource) VALUES (%s, %s, %s, %s, %s, %s, %s)",
                    GetSQLValueString($_POST['group_id'], "int"),
                    GetSQLValueString($_POST['content_id'], "int"),
                    GetSQLValueString($_POST['group_member_title'], "text"),
                    GetSQLValueString($_POST['group_order'], "int"),
                    GetSQLValueString($_POST['description'], "text"),
                    GetSQLValueString($_POST['group_direct_link'], "text"),
                    GetSQLValueString($_POST['group_member_resource'], "int"));

    $result = processQuery($insertSQL);
}

function groupList($siteID) {
    return siteCategoriesByItem("group", $siteID);
}

function groupMemberFindByGroup($groupId) {
    $q = "select * from group_member where group_id=$groupId";
    $result = processQuery($q);
    return $result;
}

function groupMemberDetail($groupMemId) {
    $q = "select * from group_member where group_member_id=$groupMemId";
    $result = processQuery($q);
    return $result;
}

//</editor-fold>


function drawSiteMap($siteLinks) {
    $siteLink = mysql_fetch_assoc($siteLinks);
    do {
        $url = "?page=page_cat&index=" . $_GET["index"] . "&itemid=" . $siteLink["content_id"];
        if ($siteLink["content_id"] > 0) {
            $pg = "?page=page_cat&index=" . $_GET["index"] . "&cid=" . $siteLink["content_id"];
            $ct = "pages/category_add.php?aj&pid=" . $siteLink["category_id"]
?>
            <li>
                <div class="sub_link"> <input type="checkbox" value="<?php echo $siteLink["category_id"] ?>" name="pc<?php echo $siteLink["content_id"] ?>" /> <a href="<?php echo $url; ?>" title="<?php echo $siteLink["page_title"]; ?>"> <?php echo $siteLink["page_title"]; ?></a>
                    <a href="<?php echo $ct; ?>" rel="facebox" class="cat first" title="Add to Category &raquo; <?php echo $siteLink["page_title"]; ?>">+ Category</a><a href="<?php echo $pg; ?>" title="add page to &raquo;  <?php echo $siteLink["page_title"]; ?>"   class="page">+ Page</a>
                </div>
    <?php
            $r = getContentByCat($siteLink["content_id"], 0, "NO");
            if (mysql_fetch_assoc($r) > 0) {
    ?>              <ul class="sub">
    <?php drawContent($r); ?>
                </ul>
    <?php
            }
            $subLinks = getSubCategoryFind($siteLink["category_id"], 0, "NO");
            if (mysql_num_rows($subLinks) > 0) {
    ?>               <ul class="sub">
    <?php drawSiteMap($subLinks); ?>
                </ul>
    <?php } ?>
        </li>
<?php
        }
    } while ($siteLink = mysql_fetch_assoc($siteLinks));
}

function drawContent($siteLinks) {
    $siteLink = mysql_fetch_assoc($siteLinks);
    do {
        if ($siteLink["category_id"] > 0) {
            $url = "?page=page_cat&index=" . $_GET["index"] . "&itemid=" . $siteLink["content_id"];
            $pg = "?page=page_cat&index=" . $_GET["index"] . "&cid=" . $siteLink["content_id"];
?>          <li>
                <div class="sub_link">
                    <input type="checkbox" value="<?php echo $siteLink["category_id"] ?>" name="pc<?php echo $siteLink["category_id"] ?>" /><a href="<?php echo $url; ?>" title="<?php echo $siteLink["page_title"]; ?>"> <?php echo $siteLink["page_title"]; ?></a>
                    <a href="<?php echo $pg; ?>" class="page first" title="add page to &raquo;  <?php echo $siteLink["page_title"]; ?>">+ Page</a>
                </div>
    <?php
            $subLinks = getContentByCat($siteLink["category_id"], 0, "NO");
            //  echo mysql_num_rows($subLinks);
    ?>          </li>
<?php
        }
    } while ($siteLink = mysql_fetch_assoc($siteLinks));
}

//<editor-fold desc="USer page validation">
function validateUserPage() {
    if (isset($_GET["page"])) {
        GLOBAL $utility;
        if (!inUserFunctions($_GET["page"])) {
            $utility->redirect("?er=noaccess");
        }
    }
}

function inUserFunctions($page) {
    $userPrivileges = getUserTask();
    $valid = false;
    for ($i = 1; $i <= count($userPrivileges); $i++) {

        if (isset($_GET["index"])) {
            if (strtolower($userPrivileges[$i]["page"]) == strtolower($page) && $_GET["index"] == $userPrivileges[$i]["index"])
                return true;
        }
        else if (strtolower($userPrivileges[$i]["page"]) == strtolower($page)) {
            return true;
        }
    }return $valid;
}

//</editor-fold>

function uploadFiles(){
$imageNum = $_REQUEST['uploadnum'];
$dirname = $_POST['dirname'];
$uploadDiv = "";

if (!is_dir("../" . $dirname)) {
    mkdir("../" . $dirname);
}

$dirname.="/";
for ($i = 1; $i <= $imageNum; $i++) {

    if (($_FILES["file$i"]["size"] < 200000000)) {
        $destination = $dirname . $_FILES["file$i"]["name"]; // . $filenames[$f] . "/" . $lastResource . "_" . $filenm;
        if (move_uploaded_file($_FILES["file$i"]["tmp_name"], "../" . $destination)) {
            $uploadDiv.= "<div class='success'>" . $_FILES["file$i"]["name"] . " uploaded to " . $destination . "</div>";
        } else {
            $uploadDiv.= "<div class='fail'>" . $_FILES["file$i"]["name"] . " unable to uploaded to " . $destination . "</div>";
        }
    }
}
return $uploadDiv;
}




function uploadFile($file, $fileType, $uploadDestination, $maxSize=200000000, $rename="", $prePendExisitngName=true, $resize=0) {
    global $utility;
    if ((@$_FILES["$file"]["size"] < $maxSize)) {
        //echo "<br />Type : ".$_FILES["file$i"]["type"];
        //echo "<br />Size : ".$_FILES["file$i"]["size"];
 $f = 1;
            $fileExtensionStarts = strrpos($_FILES["$file"]["name"], '.');
            $fileNameOnly = $utility->urlFriendly(substr($_FILES["$file"]["name"], 0, $fileExtensionStarts), "_");
            $fileExtension = substr($_FILES["$file"]["name"], $fileExtensionStarts);
            $filenm = "" . $rename;
            if ($prePendExisitngName) {
                $filenm = $rename . $fileNameOnly;
            }
            $filenm = "/" . $filenm . $fileExtension;

        if (( @$_FILES["$file"]["type"] == "image/gif")
                || (@$_FILES["$file"]["type"] == "image/jpeg") || (@$_FILES["file$i"]["type"] == "image/png")
                || (@$_FILES["$file"]["type"] == "image/pjpeg")) {
            // echo "Image found";
            //$filetype = $IMAGES;

            if ($resize > 0) {
                $filethumb = new ThumbnailImageToFile($_FILES["$file"]["tmp_name"], $uploadDestination . $filenm, $resize);
                $filethumb->getImage();
                return "" . $uploadDestination . $filenm;
            } else {
                if (move_uploaded_file($_FILES["$file"]["tmp_name"], "" . $uploadDestination . $filenm))
                    return "" . $uploadDestination . $filenm;
                else
                    return "Unable to upload file " . $uploadDestination . $filenm;
            }
        }else{
             if (move_uploaded_file($_FILES["$file"]["tmp_name"], "" . $uploadDestination . $filenm))
                    return "" . $uploadDestination . $filenm;

        }
    }else {
//// echo $filetype." - ||- ";
//     //   echo $filenames[$f] . " $f " . $_FILES["file$i"]["type"];
//        if ($filetype != NULL && $filetype > 0) {
//            // echo "FIle type error";
//            if ($_FILES["file$i"]["error"] > 0) {
//                $msg = "Return Code:  " . $_FILES["file$i"]["error"] . " File had errors<br />";
//            } else {
//
//                $lastResource = getLastResource();
//                $lastResource+=1;
//                $fileExtensionStarts = strrpos($_FILES["file$i"]["name"], '.');
//                $fileNameOnly = $utility->urlFriendly(substr($_FILES["file$i"]["name"], 0, $fileExtensionStarts), "_");
//                $fileExtension = substr($_FILES["file$i"]["name"], $fileExtensionStarts);
//                $filenm = $fileNameOnly . $fileExtension;
//
//
//                if ($filenames[$f] == "images") {
//                    $destination = "resources/" . $filenames[$f] . "/" . $plusloc . "" . $lastResource . "_" . $filenm;
//                }
//                else
//                    $destination = "resources/" . $filenames[$f] . "/" . $lastResource . "_" . $filenm;
//                move_uploaded_file($_FILES["file$i"]["tmp_name"], "../" . $destination);
//                //if($filenames[$f]=="images")
//                $img = $filenames[$f] . "/" . $plusloc . $lastResource . "_" . $filenm;
//                //  else
//                //     $img = $filenames[$f]."/".$lastResource."_".$filenm;
//
//                $insertSQL = sprintf("INSERT INTO resource (category_id,resource_url,resource_description) VALUES (%s, %s, %s)",
//                                GetSQLValueString($filetype, "text"),
//                                GetSQLValueString($img, "text"),
//                                GetSQLValueString(stripUslessCharacters($_POST["pdesc" . $i]), "text"));
//
//                mysql_select_db($database_conn, $conn);
//                $Result1 = mysql_query($insertSQL, $conn) or die(mysql_error());
//                $arnt = mysql_insert_id($conn);
//                if ($_POST['resourceonly'] != "yes" && !isset($_POST['resourceonly'])) {
//                    addResources($arnt, $contentid);
//                }
//                $cnt++;
//            }
    }
}
?>
